<template>
	<view class="login">
		<!-- 自定义导航栏 -->
		<uniNavBar
			:title='pageType == "my"?"修改用户信息":"添加用户信息"' 
			leftIcon='left'
			leftText="返回"
			:right-text=' isNavBar?"完成":"编辑"   ' 
			fixed='true'
			status-bar='true'
			@clickRight= 'isNavBar = !isNavBar'
			@clickLeft="Back"
		></uniNavBar>
		<view class="main">
			<Lines></Lines>
			<view class="user_avatar">
				<view class="">
					<block v-for="(image,index) in imageList" :key="index">
						<view class="dle-image">
							<uni-icons @tap="delimage(index)" class="del" size="20" type="clear" v-if="pageType !='my'"></uni-icons>
							<image ref="files" class="avatar" :src="image" :data-src="image" @tap="previewImage(index)">
							</image>
						</view>
					</block>
					<view v-show="imageList.length < 1" class="selectImage">
						<view class="user_avatar" @tap="chooseImage"></view>
					</view>
				</view>
			</view>
			<Lines></Lines>
			<view class="user-name flex">
				<text>姓名：</text>
				<input type="text" placeholder="请输入用户名" v-model="userName" :disabled="!isNavBar"/>
			</view>
			<Lines></Lines>
			<view class="user-pwd flex">
				<text>密码：</text>
				<input type="text" placeholder="请输入密码" v-model="userPwd" :disabled="!isNavBar"/>
			</view>
			<Lines></Lines>
			<view class="user-nickanme flex">
				<text>昵称：</text>
				<input type="text" placeholder="请输入昵称" v-model="nickName" :disabled="!isNavBar"/>
			</view>
			<Lines></Lines>
		</view>
		<view class="add-goods">
			<view class="add-goods-item" @tap="define">确定</view>
		</view>
	</view>
</template>

<script>
	import uniNavBar from '@/components/uni/uni-nav-bar/uni-nav-bar.vue'
	import $http from '../../common/api/request.js'
	import Lines from '../../components/common/Lines.vue'
	import {
		mapMutations,
		mapState
	} from 'vuex'
	import {
		v4 as uuidv4
	} from 'uuid'
	export default {
		data() {
			return {
				isNavBar:false,
				// 用户名
				userName: "",
				// 密码
				userPwd: "",
				// 昵称
				nickName: "",
				// 电话
				phone: '',
				// 验证码
				code: '',
				// 用户头像
				imageList: [],
				//七牛云的外链
				qiniuBucketURLPrefix: 'verification.zydxydsxt.top/',
				//存储外链
				partImgUrl: [],
				//存储的用户头像
				imgUrl: '',
				// 页面类型
				pageType: ''
			}
		},
		components: {
			Lines,
			uniNavBar
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo
			})
		},
		onLoad(e) {
			this.phone = e.phone,
				this.code = e.code
			if (e.pageType) {
				this.pageType = e.pageType
			}else {
				this.isNavBar = true
			}
			if (this.userInfo) {
				this.userName = this.userInfo.userName,
				this.userPwd = this.userInfo.userPwd,
				this.nickName = this.userInfo.nickName,
				this.imageList.push(this.userInfo.imgUrl)
			}
		},
		methods: {
			...mapMutations(['login']),
			Back(){
				uni.navigateBack({
					delta:1
				})
			},
			define(){
				this.Registered()
			},
			// 注册 登录
			Registered() {
				if (this.userName != '' && this.userPwd != '' && this.nickName != '') {
					if(this.pageType == 'my'){
						this.updateUserInfo()
					}else {
						this.setUserInfo()
					}
				} else {
					uni.showToast({
						title: "数据不能为空哦",
						icon: 'none'
					})
				}
			},
			// 修改用户信息
			updateUserInfo(){
				let image = this.userInfo.imgUrl
				
				$http.request({
					url:'/Edituser',
					method:'POST',
					header:{
						token:true,
					},
					data:{
						userName: this.userName,
						userPwd: this.userPwd,
						nickName: this.nickName,
						imgUrl:image
					}
				}).then((res)=>{
					if(res.protocol41){
						$http.request({
							url: "/login",
							method: "POST",
							data: {
								userName: this.userName,
								userPwd: this.userPwd,
								imgUrl: image
							}
						}).then((res) => {
							// 保存用户信息
							this.login(res.data)
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
							uni.hideLoading()
							uni.navigateBack({
								delta:1
							})
						}).catch(() => {
							uni.showToast({
								title: "请求失败",
								icon: "none"
							})
						})
					}
				}).catch(()=>{
					uni.showToast({
						title:'修改数据失败',
						icon:'none'
					})
				})
			},
			// 设置用户信息
			setUserInfo(){
				$http.request({
					url: "/addUser",
					method: "POST",
					data: {
						userName: this.userName,
						userPwd: this.userPwd,
						nickName: this.nickName,
						phone: this.phone,
						code: this.code,
						imgUrl: this.imgUrl
					}
				}).then((res) => {
					this.userName = res.data.userName;
					this.userPwd = res.data.userPwd;
					this.imgUrl = this.partImgUrl[0].imgUrl
					// 注册成功，提示信息
					if (res.success) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						// 注册成功之后直接登录 调用登录接口
						$http.request({
							url: "/login",
							method: "POST",
							data: {
								userName: this.userName,
								userPwd: this.userPwd,
								imgUrl: this.imgUrl
							}
						}).then((res) => {
							// 保存用户信息
							this.login(res.data)
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
							uni.hideLoading()
							uni.reLaunch({
								url: "/pages/index/index"
							})
						}).catch(() => {
							uni.showToast({
								title: "请求失败",
								icon: "none"
							})
						})
					}
				}).catch(() => {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					})
				})
			},
			// 删除图片
			delimage(index) {
				this.imageList.splice(index, 1);
			},
			// 预览图片
			previewImage(index) {
				// 如果处于完成状态下点击---预览 否则调用函数
				if(!this.isNavBar){
					uni.previewImage({
						urls: this.imageList, //需要预览的图片连接列表
						current: this.imageList[index] //当前显示的图片连接
					})
				}else {
					this.chooseImage()
				}
			},
			chooseImage() {
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数
					sizeType: ['compressed'], //original原图 compressed压缩图
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机
					// 成功则返回图片的本地文件路径列表 tempFilePaths
					success: (chooseImageRes) => {
						this.imageList.push(...chooseImageRes.tempFilePaths)
						const tempFilePaths = chooseImageRes.tempFilePaths;
						this.imageList.forEach((item, index) => {
							$http.request({
								url: '/storeToken',
								method: 'POST'
							}).then((res) => {
								// 唯一码
								const uuid = uuidv4()
								let uploadMsg = res;
								let uniqueCode = uuid;
								let postUrl = 'http://upload-z2.qiniu.com'
								uni.uploadFile({
									url: postUrl,
									fileType: "image",
									filePath: item,
									name: 'file',
									formData: {
										'key': uniqueCode.slice(0, 10),
										'token': uploadMsg
									},
									// 经过escape()转转义之后的文件名和图片链接一部分一致
									success: (uploadFileRes) => {
										let key = JSON.parse(uploadFileRes.data)
											.key
										let partImgUrl = escape(uniqueCode.slice(0,
											10));
										this.partImgUrl.push({
											imgUrl: 'http://' + this
												.qiniuBucketURLPrefix +
												partImgUrl
										})
										if(this.pageType === 'my'){
											this.imageList = []
											this.imageList.push(this.partImgUrl[0].imgUrl)
											this.userInfo.imgUrl = this.partImgUrl[0].imgUrl
										}else {
											this.imgUrl = this.partImgUrl[0].imgUrl
										}
									},
									fail: (err) => {
										console.log('fail', err);
									}
								})

							}).catch((err) => {
								console.log(err);
							})
						})
					}
				})
			}
		}
	}
</script>

<style scoped>
	.flex {
		height: 60rpx;
		padding-left: 30rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.login {}

	.selectImage {
		width: 120rpx;
		height: 120rpx;
		border-radius: 100%;
		border: 2rpx solid #ccc;
	}

	.user_avatar {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 160rpx;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 100%;
		border: 2rpx solid #ccc;
	}

	.dle-image {
		position: relative;
	}

	.del {
		position: absolute;
		top: -10rpx;
		right: -20rpx;
	}
	.add-goods{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 80rpx;
		background-color: #49bdfb;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
	}
</style>